package _2_面向对象._1_继承;

import org.junit.jupiter.api.Test;

public class Tests {

    //----------------------------------------
    //   向上转型
    //----------------------------------------

    /**
     * 向上转型
     *
     * 定义：把一个子类类型安全地变为父类类型的赋值，被称为向上转型（upcasting）。
     *
     * 目的：向上转型实际上是把一个子类型安全地变为更加抽象的父类型
     */
    @Test
    public void Upward(){
        //Student继承自Person，因此，它拥有Person的全部功能
        Student student = new Student();
        student.printStu();

        Person person1 = new Student();
        Student student1 = (Student)person1;
        student1.printStu();

    }

    /**
     *
     */
    @Test
    public void Upward2(){

        //继承树是Student > Person > Object，所以，可以把Student类型转型为Person，或者更高层次的Object
        Student student = new Student();
        Person person = student;
        Object object1 = person;
        Object object2 = student;
    }

    //----------------------------------------
    //   向下转型
    //----------------------------------------

    @Test
    public void downcast(){
        Person person = new Person();
        Person personStu = new Student();//向上转型

//        Student student = (Student)person;//报异常：java.lang.ClassCastException
        Student student1 = (Student)personStu;
    }

    @Test
    public void downcast2(){
        Person person = new Person();
//        System.out.println(person instanceof Person);
        System.out.println(person instanceof Student);

        Student student = new Student();
        System.out.println(student instanceof Person);
    }

    //----------------------------------------
    //   区分继承和组合
    //----------------------------------------

}
